import Vue from 'vue'
import Vuex from 'vuex'
import randomstring from 'randomstring'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    notes: [
      {
        id: '001',
        content: '我学会了Vuex的三个重要组成部门：state(getters), mutations, actions'
      },
      {
        id: '002',
        content: 'getters如何传参——在getters函数里返回一个函数，这个函数是可以接收组件传递过来的参数的。'
      },
    ]
  },
  mutations: {
    addNote(state, content) {
      const obj = {
        id: randomstring.generate(7),
        content
      }
      state.notes.unshift(obj)
    },

    deleteNote(state, id) {
      // 方法一：
      // const newNotes = state.notes.filter(note => note.id !== id)
      // state.notes = newNotes

      // 方法二：
      const index = state.notes.findIndex(note => note.id === id)
      state.notes.splice(index, 1)
    },

    saveNote(state, payload) {
      const { id, note } = payload
      const obj = state.notes.find(note => note.id === id)
      obj.content = note
    }
  },
  getters: {
    itemsCount(state) {
      return state.notes.length
    },
    charactorCount(state) {
      return state.notes.reduce((sum, note) => {
        sum += note.content.length
        return sum
      }, 0)
    }
  }
})
